﻿namespace MyWebLog.Controllers
{
    using MyWebLog.Logic.Services;
    using MyWebLog.Models;
    using MyWebLog.Models.Admin;
    using MyWebLog.Models.UI;
    using MyWebLog.Properties;
    using System;
    using System.Web;
    using System.Web.Mvc;

    /// <summary>
    /// Controller for /Admin URLs
    /// </summary>
    public class AdminController : MyWebLogController
    {
        //
        // GET: /Admin/Login
        [HttpGet]
        public ActionResult Login()
        {
            var form = new LoginForm();

            if (null != Session[SessionKey.REDIRECT_URL])
            {
                form.RedirectURL = Session[SessionKey.REDIRECT_URL] as string;
                Session[SessionKey.REDIRECT_URL] = null;
            }

            return MyWebLogView("Login", "_AdminLayout", form);
        }

        //
        // POST: /Admin/ProcessLogin
        [HttpPost]
        public ActionResult ProcessLogin(LoginForm form)
        {
            using (var data = NewDataConnection())
            {
                var service = new SecurityService(data);
                var auth = service.Login(form.EmailAddress, form.Password, CurrentBlog);

                if (null == auth)
                {
                    // Login unsuccessful
                    Messages.Add(new UserMessage
                    {
                        Type = UserMessage.MessageType.Error,
                        MessageText = Resources.LoginDeniedMessage,
                        Description = new HtmlString(Resources.LoginDeniedDescription)
                    });

                    Session[SessionKey.REDIRECT_URL] = form.RedirectURL;
                    return RedirectToAction("Login");
                }

                // Login successful!
                CurrentAuthorization = auth;

                Messages.Add(new UserMessage
                {
                    Type = UserMessage.MessageType.Message,
                    MessageText = String.Format(Resources.LoginSuccessful, CurrentBlog.Name)
                });
            }

            if (null == form.RedirectURL)
                return RedirectToAction("Dashboard");

            return Redirect(form.RedirectURL);
        }

        //
        // GET: /Admin/Dashboard
        [HttpGet]
        public ActionResult Dashboard()
        {
            return MyWebLogView("Dashboard", "_AdminLayout");
        }
    }
}